package com.anntly.netty.firstDemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Auther: 张文
 * @Date: 2020/5/5 15:12
 * @Description:
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程组
        // 1. bossGroup:只负责接受请求
        // 2. workGroup:真正和客户端业务处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        // 服务器启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            // 设置
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class) // 使用NIOSocketChannel作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 给pipeline设置处理器
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    }); // 为workGroup的EventLoop对应的管道设置处理器
            System.out.println("server is ready");
            // 启动服务器并绑定端口
            ChannelFuture cf = bootstrap.bind(6668).sync();

            cf.addListener(new ChannelFutureListener() {
                               public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                   if(channelFuture.isSuccess()){
                                       System.out.println("监听端口成功");
                                   }else {
                                       System.out.println("监听端口失败");
                                   }
                               }
                           });
            cf.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
        }
    }
}
